package kamikaze.service.product;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import kamikaze.entity.Order;
import kamikaze.entity.OrderItem;
import kamikaze.entity.Product;
import kamikaze.entity.User;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;

@ServiceConfig(path = "product/addrating", method = HttpMethod.GET)
public class ProductRatingService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {

		User user = ctx.getUserSession().asUser();

		HttpServletRequest req = ctx.getRequest();

		final Long id = Long.parseLong(req.getParameter("id"));
		final Long orderId = Long.parseLong(req.getParameter("orderId"));

		EntityManager em = ctx.getEntityManager();
		Query q = ctx.getEntityManager().createQuery(
				"Select p from Product p where p.productId= :productId and deleted=false");
		q.setParameter("productId", id);

		Product product = (Product) q.getSingleResult();

		// check i have purchased before

		Order order = em.find(Order.class, orderId);

		checkPurchase(order, user.getId(), id);

		req.setAttribute("product", product);

		return "product/addrating";

	}

	private void checkPurchase(Order order, Long userId, Long productId) {
		if (order == null) {
			throw new ServiceException("no such order");
		}

		if (order.getUserId() != userId) {
			throw new ServiceException("not your order");
		}

		for (OrderItem item : order.getItemList()) {
			if (item.getProductId().equals(productId)) {
				return;
			}
		}

		throw new ServiceException("never buy");

	}

}
